import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

// state对象
const state = {
  // 初始化状态
  token: getToken(),
  name: '',
  nickname: '',
  avatar: '',
  roles: [],
  user_permissions: [],
  projects: []
}

// 更新state函数对象
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_NICKNAME: (state, nickname) => {
    state.nickname = nickname
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.user_permissions = permissions
  },
  SET_PROJECTS: (state, projects) => {
    state.projects = projects
  }
}
// 多个事件函数回调对象
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { token } = response
          commit('SET_TOKEN', token)
          setToken(token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const {
            username,
            nickname,
            headImgUrl,
            permissions,
            projects
          } = response
          // 直接把角色设置成admin,用后端动态路由控制
          const roles = ['admin']
          if (!roles || roles.length <= 0) {
            reject('getInfo: roles必须是非空数组!')
          }
          commit('SET_ROLES', roles)
          commit('SET_NAME', username)
          commit('SET_NICKNAME', nickname)
          commit('SET_AVATAR', headImgUrl)
          commit('SET_PERMISSIONS', permissions)
          commit('SET_PROJECTS', projects)
          // resolve(data)
          resolve({ roles })
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resetRouter()
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 移除 token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
